package com.marui.ch2.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author marui
 * @date 12:04 2020/5/17
 * @since 1.0
 */
public class MyForkJoin extends RecursiveTask<Integer> {

    private Integer start;
    private Integer end;
    /**
     * 阈值
     */
    private static final int THRESHOLD = 2 ;

    public MyForkJoin(Integer start, Integer end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {

        int sum = 0;
        if(end - start <= THRESHOLD){
            for (int i = start ; i <= end ; i++) {
                sum += i;
            }
        } else {
            int mid = (end + start) / 2;
            MyForkJoin left = new MyForkJoin(start,mid);
            MyForkJoin right = new MyForkJoin(mid+1,end);
            left.fork();
            right.fork();
            sum = left.join() + right.join();
        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool pool = new ForkJoinPool();
        MyForkJoin myForkJoin = new MyForkJoin(1, 100);
        ForkJoinTask<Integer> submit = pool.submit(myForkJoin);
        System.out.println("结果是"+submit.get());
    }
}
